package com.aynu.gulimall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.aynu.common.constant.ProductConstant;
import com.aynu.common.to.SkuHasStockVo;
import com.aynu.common.to.SkuReductionTo;
import com.aynu.common.to.SpuBoundTo;
import com.aynu.common.to.es.SKUEsModel;
import com.aynu.common.utils.R;
import com.aynu.gulimall.product.dao.SkuSaleAttrValueDao;
import com.aynu.gulimall.product.entity.*;
import com.aynu.gulimall.product.feign.CouponFeignService;
import com.aynu.gulimall.product.feign.SearchFeignService;
import com.aynu.gulimall.product.feign.WareFeignService;
import com.aynu.gulimall.product.service.*;
import com.aynu.gulimall.product.vo.*;
import com.mysql.cj.util.StringUtils;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.aynu.common.utils.PageUtils;
import com.aynu.common.utils.Query;

import com.aynu.gulimall.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;


@Service("spuInfoService")
@Slf4j
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    SpuInfoDescService spuInfoDescService;

    @Autowired
    SpuImagesService spuImagesService;

    @Autowired
    AttrService attrService;

    @Autowired
    ProductAttrValueService productAttrValueService;

    @Autowired
    SkuInfoService skuInfoService;

    @Autowired
    SkuImagesService skuImagesService;

    @Autowired
    SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    CouponFeignService couponFeignService;

    @Autowired
    private BrandService brandService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private WareFeignService wareFeignService;

    @Autowired
    private SearchFeignService searchFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    //分布式事务（适合Seata的AT模式）
    @GlobalTransactional
    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVo vo) {
        //1、保存spu基本信息 pms_spu_info
        SpuInfoEntity infoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(vo,infoEntity);
        infoEntity.setCreateTime(new Date());
        infoEntity.setUpdateTime(new Date());
        this.saveSpuBaseInfo(infoEntity);
        log.info("infoEntity:{} ",infoEntity);

        //2、保存spu描述图片 pms_spu_info_desc
        List<String> decript = vo.getDecript();
        SpuInfoDescEntity descEntity = new SpuInfoDescEntity();
        descEntity.setSpuId(infoEntity.getId());
        descEntity.setDecript(String.join(",",decript));
        spuInfoDescService.saveSpuInfoDesc(descEntity);
        System.out.println("descEntity  "+descEntity);

        //3、保存spu图片集 pms_spu_images
        List<String> images = vo.getImages();
        spuImagesService.saveImages(infoEntity.getId(),images);
        System.out.println("images   "+images);

        //4、保存spu规格参数 pms_product_attr_value
        List<BaseAttrs> baseAttrs = vo.getBaseAttrs();
        List<ProductAttrValueEntity> collect = baseAttrs.stream().map(attr -> {
            ProductAttrValueEntity productAttrValueEntity = new ProductAttrValueEntity();
            productAttrValueEntity.setAttrId(attr.getAttrId());

            AttrEntity attrEntity = attrService.getById(attr.getAttrId());
            productAttrValueEntity.setAttrName(attrEntity.getAttrName());

            productAttrValueEntity.setQuickShow(attr.getShowDesc());
            productAttrValueEntity.setAttrValue(attr.getAttrValues());
            productAttrValueEntity.setSpuId(infoEntity.getId());

            return productAttrValueEntity;
        }).collect(Collectors.toList());
        productAttrValueService.saveProductAttr(collect);
        System.out.println("collect  "+collect);

        //5、保存spu的积分信息 gulimall_sms->sms_spu_bounds
        Bounds bounds = vo.getBounds();
        SpuBoundTo spuBoundTo = new SpuBoundTo();
        BeanUtils.copyProperties(bounds,spuBoundTo);
        spuBoundTo.setSpuId(infoEntity.getId());

        System.out.println("spuBoundTo  "+spuBoundTo);
        log.info("调用远程接口：保存积分接口");
        R r = couponFeignService.saveSpuBound(spuBoundTo);
        if (r.getCode()!=0){
            log.error("保存spu的积分信息,远程调用失败");
        }


        //6、保存当前spu的sku信息
        List<Skus> skus = vo.getSkus();
        if (skus!=null && skus.size()>0)
        {
            skus.forEach(sku->{
                String defaultImg="";
                for (Images image:sku.getImages()){
                    if (image.getDefaultImg()==1)
                    {
                        defaultImg=image.getImgUrl();
                    }
                }

                //6.1、保存sku的基本信息 pms_sku_info
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(sku,skuInfoEntity);
                skuInfoEntity.setBrandId(infoEntity.getBrandId());
                skuInfoEntity.setCatalogId(infoEntity.getCatalogId());
                skuInfoEntity.setSaleCount(0L);
                skuInfoEntity.setSpuId(infoEntity.getId());
                skuInfoEntity.setSkuDefaultImg(defaultImg);

                log.info("保存sku信息：{}",skuInfoEntity);
                skuInfoService.saveSkuInfo(skuInfoEntity);

                Long skuId = skuInfoEntity.getSkuId();

                //6.2、保存sku的图片 pms_sku_images
                List<SkuImagesEntity> imagesEntities = sku.getImages().stream().map(img -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setSkuId(skuId);
                    skuImagesEntity.setImgUrl(img.getImgUrl());
                    skuImagesEntity.setDefaultImg(img.getDefaultImg());
                    return skuImagesEntity;
                }).filter(entity->{
                    //返回true，就是需要，返回false就是剔除
                    return !StringUtils.isEmptyOrWhitespaceOnly(entity.getImgUrl());
                }).collect(Collectors.toList());
                skuImagesService.saveBatch(imagesEntities);
                //TODO 没有图片路径，无需保存

                //6.3、保存sku的销售属性信息 pms_sku_sale_attr_value
                List<SkuSaleAttrValueEntity> saleAttrValueEntities = sku.getAttr().stream().map(attr -> {
                    SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(attr, skuSaleAttrValueEntity);
                    skuSaleAttrValueEntity.setSkuId(skuId);
                    return skuSaleAttrValueEntity;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(saleAttrValueEntities);
                System.out.println("saleAttrValueEntities  "+saleAttrValueEntities);

                /*6.4、保存sku的优惠，满减等信息 gulimall_sms->
                【sms_sku_ladder（打折）/sms_sku_full_reduction（满减）/sms_member_price（会员价）】*/
                SkuReductionTo skuReductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(sku,skuReductionTo);
                skuReductionTo.setSkuId(skuId);
                if (skuReductionTo.getFullCount()>0 || skuReductionTo.getFullPrice().compareTo(new BigDecimal("0")) == 1)
                {
                    R r1 = couponFeignService.saveSkuReduction(skuReductionTo);
                    if (r1.getCode()!=0){
                        log.debug("保存sku的优惠，满减等信息,远程调用失败");
                    }
                }

                System.out.println("skuReductionTo  "+skuReductionTo);
            });

            System.out.println("success");
        }

        //6.2、保存sku的图片 pms_sku_images
        //6.3、保存sku的销售属性信息 pms_sku_sale_attr_value
        //6.4、保存sku的优惠，满减等信息 gulimall_sms->【sms_sku_ladder（打折）/sms_sku_full_reduction（满减）/sms_member_price（会员价）】
    }

    @Override
    public void saveSpuBaseInfo(SpuInfoEntity spuInfoEntity) {
        baseMapper.insert(spuInfoEntity);
    }

    @Override
    public PageUtils queryPagebyCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<>();
        /*
        * status: 0
          key:
          brandId: 4
          catelogId: 225
        * */
        String key = (String) params.get("key");
        if (!StringUtils.isEmptyOrWhitespaceOnly(key)){
            wrapper.and(w->{
                w.eq("id",key).or().like("spu_name",key);
            });
        }
        String status = (String) params.get("status");
        if (!StringUtils.isEmptyOrWhitespaceOnly(status)){
            wrapper.eq("publish_status",status);
        }
        String brandId = (String) params.get("brandId");
        if (!StringUtils.isEmptyOrWhitespaceOnly(brandId) && !"0".equals(brandId)){
            wrapper.eq("brand_id",brandId);
        }
        String catelogId = (String) params.get("catelogId");
        if (!StringUtils.isEmptyOrWhitespaceOnly(catelogId) && !"0".equals(catelogId)){
            wrapper.eq("catalog_id",catelogId);
        }

        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
               wrapper
        );
        return new PageUtils(page);
    }

    @Override
    @Transactional
    public void up(Long spuId) {

        //1、查询当前spuid对应的sku信息，品牌名字
        List<SkuInfoEntity> skuInfoEntities = skuInfoService.getSkusBySpuId(spuId);

        //收集skui
        List<Long> skuIds = skuInfoEntities.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());

        log.info("查询当前sku的所有可以用来被检索的规格属性");
        List<ProductAttrValueEntity> baseAttrValue = productAttrValueService.baseAttrlistforspu(spuId);
        List<Long> attrIds = baseAttrValue.stream().
                map(ProductAttrValueEntity::getAttrId).collect(Collectors.toList());

        log.info("根据attrid集合，查询attr信息");
        List<Long> attrSearchIds = attrService.selectSearchAttrs(attrIds);

        //查找出来需要检索的规格属性entity
        Set<Long> idSet = new HashSet<>(attrSearchIds);
        List<SKUEsModel.Attrs> esAttrs = baseAttrValue.stream().filter(item -> {
            return idSet.contains(item.getAttrId());
        }).map(item -> {
            //将attr实体类，转换成es的Attr类
            SKUEsModel.Attrs esAttr = new SKUEsModel.Attrs();
            BeanUtils.copyProperties(item, esAttr);
            return esAttr;
        }).collect(Collectors.toList());

        //TODO 发送远程调用，库存系统查询是否有库存
        log.info("发送远程调用，库存系统查询是否有库存,skuIds:{}",skuIds);
        Map<Long, Boolean> stockMap = null;
        try {
            R skuHasStock = wareFeignService.getSkuHasStock(skuIds);
            TypeReference<List<SkuHasStockVo>> typeReference = new TypeReference<List<SkuHasStockVo>>() {};
            List<SkuHasStockVo> data = skuHasStock.getData(typeReference);
            stockMap = data.stream().collect(Collectors.toMap(item->item.getSkuId(), item->item.getHasStock()));
        } catch (Exception e) {
            e.printStackTrace();
            log.error("库存服务查询异常:原因:{}",e);
        }

        //2、封装每个sku信息
        Map<Long, Boolean> finalStockMap = stockMap;
        List<SKUEsModel> skuEsModels = skuInfoEntities.stream().map((sku) -> {
            //组装需要的数据
            SKUEsModel skuEsModel = new SKUEsModel();
            BeanUtils.copyProperties(sku, skuEsModel);

            //如果调用库存失败，则有库存
            if (finalStockMap==null){
                skuEsModel.setHasStock(true);
            }else {
                skuEsModel.setHasStock(finalStockMap.get(sku.getSkuId()));
            }

            //设置属性对拷不能完成的数据
            skuEsModel.setSkuPrice(sku.getPrice());
            skuEsModel.setSkuImg(sku.getSkuDefaultImg());

            //TODO 热度评分，默认为0
            skuEsModel.setHotScore(0L);

            //查询品牌的和分类的名字
            BrandEntity brandEntity = brandService.getById(skuEsModel.getBrandId());
            CategoryEntity categoryEntity = categoryService.getById(skuEsModel.getCatalogId());
            skuEsModel.setBrandName(brandEntity.getName());
            skuEsModel.setBrandImg(brandEntity.getLogo());
            skuEsModel.setCatalogName(categoryEntity.getName());

            //设置规格的检索属性
            skuEsModel.setAttrs(esAttrs);

            return skuEsModel;
        }).collect(Collectors.toList());

        //TODO 发送es请求
        R r = searchFeignService.productStatusUp(skuEsModels);
        if (r.getCode() == 0){
            //远程调用成功
            //TODO 修改当前spu状态
            baseMapper.updateStatus(spuId, ProductConstant.StatusEnum.SPU_UP.getCode());
        }else {
            //远程调用失败
            //TODO 重复调用，接口幂等性，重试机制？xxx
            /**
             * Feign的调用流程
             * 1、构造请求数据，将对象转为json
             *      RequestTemplate template = new bulidTemplateFromArgs.create(argv)
             * 2、发送请求进行执行（执行成功会解码响应数据）
             *      executeAndDecode(template)
             * 3、执行请求会有重试机制(默认为关闭，开启后默认重试5次)
             *      while(true){
             *          try{
             *              executeAndDecode(template)
             *          }
             *          catch(e){
             *              try{retryer.continueOrPropagate(e)}catch(e){throw ex;};
             *              throw ex;
             *              continue;
             *          }
             *      }
             */
        }
    }

    @Override
    public SpuInfoEntity getSpuInfoBySkuId(Long skuId) {
        SkuInfoEntity skuInfoEntity = skuInfoService.getById(skuId);
        SpuInfoEntity spuInfoEntity = getById(skuInfoEntity.getSpuId());
        return spuInfoEntity;
    }

}